package com.raos.example;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片压缩工具类
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2023-08-17 19:20
 */
public class PicUtils {

    /**
     * 对图片进行原比例无损压缩,压缩后覆盖原图片
     *
     * @param path
     */
    private static void doWithPhoto(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        BufferedImage image = null;
        FileOutputStream os = null;
        try {
            image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bfImage.getGraphics()
                    .drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            os = new FileOutputStream(path);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
            encoder.encode(bfImage);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        long millis = System.currentTimeMillis();
        String file = "D:\\raos\\工作目录\\2023年\\8月\\0814-0820\\宝山pc端logo1.png";
        doWithPhoto(file);
        System.out.println("耗时毫秒数" + (System.currentTimeMillis() - millis));
        doWithPhoto("D:\\raos\\工作目录\\2023年\\8月\\0814-0820\\宝山pc端logo2.png");
        System.out.println("耗时毫秒数" + (System.currentTimeMillis() - millis));
    }
}
